package com.xzy.controller;

import com.xzy.mapper.UserEmailMapper;
import com.xzy.pojo.UserEmail;
import com.xzy.pojo.VoteUser;
import com.xzy.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserEmailController {
    @Autowired
    VoteUserService voteUserService;
    @Autowired
    TopicVoteService topicVoteService;
    @Autowired
    private ApplyAuthorService applyAuthorService;
    @Autowired
    private UserEmailService userEmailService;
    @Autowired
    SendMail sendMail;
    @RequestMapping("/applySendEmail")
    public String applySendEmail(HttpSession session,Model model,UserEmail  userEmail){
        String username=((VoteUser) session.getAttribute("loginUser")).getUsername();
        userEmail.setUsername(username);
        try{
            int res=userEmailService.insertUserEmail(userEmail);
            if(res>0) {
                model.addAttribute("AgreeAuthor","用户"+"申请邮箱祝福成功，等待超级管理员发送");
            }else {
                model.addAttribute("AgreeAuthor","用户"+"申请邮箱祝福失败，上次申请管理员还没发送");
            }
        }catch (Exception e){
            model.addAttribute("AgreeAuthor","用户"+"申请邮箱祝福失败，上次申请管理员还没发送");
        }
        return "forward:/user/ApplyAuthor";
    }
    @RequestMapping("/user/sendEmail/to")
    public synchronized String sendEmail(Model model,int nowUserEmailPage){
        try{
            if(nowUserEmailPage<=0){
                nowUserEmailPage=1;
            }
            List<UserEmail> userEmail = this.userEmailService.selectUserEmailPage((nowUserEmailPage - 1) * 5, 5);
            model.addAttribute("userEmail",userEmail);
            model.addAttribute("nowUserEmailPage",nowUserEmailPage);
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return "sendEmail";
    }
    @RequestMapping("/user/sendEmail/send")public String sendEmail(Model model,UserEmail userEmail) throws MessagingException {
            this.sendMail.sendMail(userEmail);
            int res=this.userEmailService.deleteUserEmail(userEmail.getUsername());
            if(res>0){
                model.addAttribute("sendMail","发送成功");
            }else {
                model.addAttribute("sendMail","发送失败");
            }
        return "forward:/user/sendEmail/to?nowUserEmailPage=0";
    }
}
